﻿@model CoolAgenda.ViewModels.Compromisso.CadastrarVM
@{
    ViewBag.Title = "Cadastrar Compromisso";
}

<div class="modal-header">
    <h4>Novo Compromisso</h4>
</div>
<div class="modal-body">

    @using (Html.BeginForm("Cadastrar", "Compromisso", FormMethod.Post, new { id = "EventForm", @class = "well" }))
    {
        string display = ViewData.ModelState.IsValid ? "none" : "block";
        <div class="errorbox" id="validationSummary" style="display:@display; float: right; width: 45%">
            @Html.ValidationSummary()
        </div>

        <div style="width: 50%;">
            @Html.TextBoxFor(m => m.NomeCompromisso, new { id = "nomeCompromisso", @placeholder = "Nome do Compromisso" })

            @Html.TextBoxFor(m => m.DataInicial, new { id = "txDataInicial", @class = "datetimepicker-pt-br", @placeholder = "Data Inicial" })
        </div>
        <div style="width: 100%;">
            <div style="width: 120px; text-align: center; float: left">Até</div>

            @Html.CheckBoxFor(m => m.DiaInteiro, new { @style = "float:left; margin-right: 7px; margin-left:20px" })
            <div>Dia Inteiro </div>

            @Html.TextBoxFor(m => m.DataFinal, new { id = "txDataFinal", @class = "datetimepicker-pt-br2", @placeholder = "Data Final" })

            <br />

            @Html.DropDownListFor(m => m.Cor, Model.ListarCores)
            <br />
            @Html.DropDownListFor(m => m.Grupo, Model.ListarGrupo, new { id = "mostraGrupo" })<br />


            @Html.LabelFor(m => m.IdUsuarios, new { @style = "margin-top: 3px" })
            @Html.TextBoxFor(m => m.IdUsuarios, new { id = "usuariosdoGrupo" })

            @Html.LabelFor(m => m.IdContatos, new { @style = "margin-top: 3px" })
            @Html.TextBoxFor(m => m.IdContatos, new { id = "contatoUsuario" })

        </div>
    }
</div>
<div class="modal-footer">
    <button type="button" id="btnPopupCancel" data-dismiss="modal" class="btn">Cancelar</button>
    <input type="submit" id="btnPopupSave" data-dismiss="modal" class="btn btn-primary" value="Salvar" form="EventForm" />
</div>

<script>

    //INICIALIZA O TOKEN USUARIOS DO GRUPO
    $(document).ready(function () {
        var grupoSelecionado = $('#mostraGrupo').val()
        $("#usuariosdoGrupo").tokenInput("/Compromisso/PegaUsuarios/?queryParam=q&idGrupo=" + grupoSelecionado,
            {
                queryParam: "q",
                propertyToSearch: "name",
                resultsFormatter: function (item) { return "<li>" + "<img src='" + item.url + "' title='" + item.name + "' height='25px' width='25px' style='margin-top:-25px' />" + "<div style='display: inline-block; padding-left: 10px;'><div class='full_name'>" + item.name + " </div><div class='email'>" + item.email + "</div></div></li>" },
                tokenFormatter: function (item) { return "<li><p>" + item.name + "</p></li>" },
                theme: "facebook",
                preventDuplicates: true,
            });
    });

    //INICIALIZA O TOKEN USUARIOS DO GRUPO
    $(document).ready(function () {
        $('#mostraGrupo').change(function () {
            var grupoSelecionado = $('#mostraGrupo').val()
            $('.token-input-list-facebook').remove();
            $("#usuariosdoGrupo").tokenInput("/Compromisso/PegaUsuarios/?queryParam=q&idGrupo=" + grupoSelecionado,
                {
                    queryParam: "q",
                    propertyToSearch: "name",
                    resultsFormatter: function (item) { return "<li>" + "<img src='" + item.url + "' title='" + item.name + "' height='25px' width='25px' style='margin-top:-25px' />" + "<div style='display: inline-block; padding-left: 10px;'><div class='full_name'>" + item.name + " </div><div class='email'>" + item.email + "</div></div></li>" },
                    tokenFormatter: function (item) { return "<li><p>" + item.name + "</p></li>" },
                    theme: "facebook",
                    preventDuplicates: true,
                });
        });
    });

    //INICIALIZA E POPULA TOKEN CONTATOS DO USUARIO
    $(document).ready(function () {
        $("#contatoUsuario").tokenInput("/Compromisso/PegaContatos/",
            {
                queryParam: "q",
                propertyToSearch: "name",
                resultsFormatter: function (item) { return "<li>" + "<img src='" + item.url + "' title='" + item.name + "' height='25px' width='25px' style='margin-top:-25px' />" + "<div style='display: inline-block; padding-left: 10px;'><div class='full_name'>" + item.name + " </div><div class='email'>" + item.email + "</div></div></li>" },
                tokenFormatter: function (item) { return "<li><p>" + item.name + " - " + item.email + "</p></li>" },
                preventDuplicates: true,
            });
    });


    $(document).ready(function () {
        $(".errorbox").prepend("<span class='errorimage'><span class='errorhead'>Ops, existem problemas</span></span>");
    });

    $(document).ready(function () {
        jQuery(".datetimepicker-pt-br").datetimepicker({
            lang: 'pt',
            format: 'd/m/Y H:i',
            step: 30
        });

        jQuery(".datetimepicker-pt-br2").datetimepicker({
            lang: 'pt',
            format: 'd/m/Y H:i',
            step: 30
        });

        if (isDate($("#txDataInicial").val())) {
            $("#txDataInicial").datetimepicker({
                startDate: $("#txDataInicial").val()
            });
        }
        if (isDate($("#txDataFinal").val())) {
            $("#txDataFinal").datetimepicker({
                startDate: $("#txDataFinal").val()
            });
        }
    });

    $(document).ready(function () {
        $('#btnPopupSave').click(function (e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: '@Url.Action("Cadastrar", "Compromisso")',
                data: $('form').serialize(),
                success: function (result) {
                    if (result.redirectTo) {
                        window.location.href = result.redirectTo;
                    } else {
                        $("#popupEventForm").html(result);
                    }
                },
                error: function () {

                }
            });
        });
    });


    $('#btnPopupCancel').click(function () {
        resetValidation();
        ClearPopupFormValues();
        $('#popupEventForm').hide();

    });

    function ClearPopupFormValues() {
        $('#nomeCompromisso').val("");
        $('#contatoUsuario').val("");
        $('#mostraGrupo').val("");
        $('#txDataInicial').val("");
        $('#txDataFinal').val("");
        $("#usuariosdoGrupo").tokenInput("clear");
        $("#contatoUsuario").tokenInput("clear");

    }

    function resetValidation() {
        //Remove validacao dos input-fields
        $('.input-validation-error').addClass('input-validation-valid');
        $('.input-validation-error').removeClass('input-validation-error');
        //Remove validation das mensagens dps dos input-fields
        $('.field-validation-error').addClass('field-validation-valid');
        $('.field-validation-error').removeClass('field-validation-error');
        //Remove o validation summary 
        $('.validation-summary-errors').addClass('validation-summary-valid');
        $('.validation-summary-errors').removeClass('validation-summary-errors');
        $('#validationSummary').css('display', 'none');
    }

    setTimeout(function () {
        $('.errorbox').fadeOut('slow');
    }, 6000);

    $('select[name="Cor"]').simplecolorpicker({ theme: 'regularfont' });

    //função que valida uma dateTime
    function isDate(dataHora) {
        var dataValida = true;

        try {
            var arrayDataHora = dataHora.split(" ");
            var arrayDiaMesAno = arrayDataHora[0].split("/");
            var arrayHoraMinuto = arrayDataHora[1].split(":");

            if (parseInt(arrayDiaMesAno[0]) <= 0 || parseInt(arrayDiaMesAno[0]) > 31) {
                dataValida = false;
            }
            if (parseInt(arrayDiaMesAno[1]) <= 0 || parseInt(arrayDiaMesAno[1]) > 12) {
                dataValida = false;
            }
            if (parseInt(arrayDiaMesAno[2]) <= 1900 || parseInt(arrayDiaMesAno[2]) > 3000) {
                dataValida = false;
            }
            if (parseInt(arrayHoraMinuto[0]) < 0 || parseInt(arrayHoraMinuto[0]) > 24) {
                dataValida = false;
            }
            if (parseInt(arrayHoraMinuto[1]) < 0 || parseInt(arrayHoraMinuto[1]) > 59) {
                dataValida = false;
            }
        }
        catch (err) {
            dataValida = false;
        }
        return dataValida;
    }

</script>
